package com.fll.fangyitask.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fll.fangyicommon.entity.ResultOk;
import com.fll.fangyicommon.entity.task.Learn;
import com.fll.fangyicommon.entity.task.Record;
import com.fll.fangyicommon.entity.task.Task;
import com.fll.fangyicommon.entity.user.User;
import com.fll.fangyicommon.utils.TimeUtil;
import com.fll.fangyicommon.vo.RecordVO;
import com.fll.fangyitask.config.RedisUtil;
import com.fll.fangyitask.service.LearnService;
import com.fll.fangyitask.service.RecordService;
import com.fll.fangyitask.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fll
 * create 2023/4/4
 */
@Slf4j
@RestController
@RequestMapping("/task")
public class LearnController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private LearnService learnService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RecordService recordService;

    //学习task
    @PostMapping("/learnTask")
    public ResultOk learnTask(@RequestBody Map<String,Object> params, @RequestHeader String userInfo) {

        ResultOk ok = new ResultOk<>();
        User user = null;
        List<Integer> userTaskIdList = null;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
            Integer taskId = (Integer) params.get("taskId");
            Integer subjectId = Integer.parseInt((String) params.get("subjectId"));

            //先判断learn表是否存在学习记录，存在就更新学习时间，不存在插入
            Boolean exist = learnService.isExist(user.getUserId(), taskId);
            Record record = new Record();
            record.setUserId(user.getUserId());
            record.setTaskId(taskId);
            record.setRecordTime(TimeUtil.getString(new Date()));
            recordService.addRecord(record);

            Learn learn = new Learn();
            if (exist){//存在，更新
                learn.setUserId(user.getUserId());
                learn.setTaskId(taskId);
                learn.setLearnTime(TimeUtil.getString(new Date()));
                learnService.update(learn);

                //更新redis
                userTaskIdList = taskService.getUserTaskIdList(subjectId + 1, user.getUserId());
                //拿到所有taskId再次查询学习时间
                StringBuilder taskIds = new StringBuilder("(");
                for(Integer id : userTaskIdList){
                    taskIds.append(id);
                    taskIds.append(",");
                }
                //删除最后一个'，' 再拼接')'
                taskIds.deleteCharAt(taskIds.length() - 1);
                taskIds.append(")");
                Map<String, Object> learnParam = new HashMap<>();
                learnParam.put("userId", user.getUserId());
                learnParam.put("taskIds", taskIds);
                redisUtil.setValueTime(user.getUserId() + "_taskLearn" + subjectId, learnService.getLearn(learnParam),15);

                ok.setCode(200);
                ok.setMsg("学习成功");
                return ok;
            } else {//不存在，插入
                learn.setUserId(user.getUserId());
                learn.setTaskId(taskId);
                learn.setLearnTime(TimeUtil.getString(new Date()));
                Integer num = learnService.insert(learn);
                if (num != -1){
                    //更新redis
                    userTaskIdList = taskService.getUserTaskIdList(subjectId + 1, user.getUserId());
                    //拿到所有taskId再次查询学习时间
                    StringBuilder taskIds = new StringBuilder("(");
                    for(Integer id : userTaskIdList){
                        taskIds.append(id);
                        taskIds.append(",");
                    }
                    //删除最后一个'，' 再拼接')'
                    taskIds.deleteCharAt(taskIds.length() - 1);
                    taskIds.append(")");
                    Map<String, Object> learnParam = new HashMap<>();
                    learnParam.put("userId", user.getUserId());
                    learnParam.put("taskIds", taskIds);
                    redisUtil.setValueTime(user.getUserId() + "_taskLearn" + subjectId, learnService.getLearn(learnParam),15);
                    ok.setCode(200);
                    ok.setMsg("学习成功");
                    return ok;
                }
            }
            ok.setCode(400);
            ok.setMsg("未知错误");
            return ok;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("后端异常");
            return ok;
        }
    }

    /**
     * 获取登录用户n天前task数据：应该复习总数和当天已复习数
     * 今天、昨天、前天、3天前、4天前、5天前、6天前、7天前
     */
    @GetMapping("/getLearnRecord")
    public ResultOk getLearnRecord(@RequestHeader String userInfo) {

        ResultOk ok = new ResultOk();
        User user = null;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
            List<RecordVO> recordVOList = recordService.getRecord(user.getUserId());
            if (recordVOList.size() != 0 || recordVOList != null){
                ok.setCode(200);
                ok.setMsg("获取成功");
                ok.setData(recordVOList);
                return ok;
            }
            ok.setCode(400);
            ok.setMsg("暂无学习记录");
        } catch (Exception e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("后端异常！");
            return ok;
        }
        return ok;
    }
}
